import java.util.Stack;


public class RuleTupleSelect {

	Stack<ControlElement> control ;
	Stack<String> stack ;
	Environment environment;
	
	public RuleTupleSelect(Stack<ControlElement> control, Stack<String> stack, Environment environment){
		this.control = control;
		this.stack = stack;
		this.environment = environment;
	}
	
	public static void main(String[] args) {
		Stack<ControlElement> control = new Stack<ControlElement>();
		Stack<String> stack = new Stack<String>();
		Environment environment = new Environment();
		RuleTupleSelect ruleTupFrm = new RuleTupleSelect(control, stack, environment);

		// test1 
		control.push(new ControlElement("gamma"));
		stack.push("<INT:4>");
		stack.push("$$tau::4::<INT:2>::<INT:3>::$$tau::<INT:89>::$$::<INT:1000>::$$");
		System.out.println(ruleTupFrm.checkRule());
		//ruleOP.devide();
		//ruleOP.power();
		ruleTupFrm.applyRule();
		System.out.println("Control:"+ruleTupFrm.control + " Stack:" +ruleTupFrm.stack);
	}
	
	/*
	 * $$tau::#::<INT:2>::<STR::'rtm'$$>
	 * remember: tuples are numbered from 1,2,3...
	 */
	public void applyRule() {
		assert(control.peek().content.equals("gamma")):"apply Tuple selection: gamma expected";
		control.pop();
		String tuple = stack.pop();
		StackTupleHandler tupleObject = new StackTupleHandler(tuple);
		if (checkInt(stack.peek()) == false)
		{
			System.out.println("tuple selection needs a integer");
		}
		
		int i = getInt(stack.pop());
		String resultPiece = tupleObject.getPiece(i);
		stack.push(resultPiece);
	}
	
	/*
	 * tuple order
	 * $$tau::#::???::....::<INT:3>::$$
	 * also think about nil and empty
	 * 1. $$tau
	 * 2. order
	 * 3. element1
	 * as soon as piecePointer is equal ith, current piece is the required piece 
	 */
	
	
	private int getInt(String op) {
		String intPart = op.split(":")[1];
		intPart = intPart.substring(0, intPart.length()-1);
		int result = Integer.parseInt(intPart);
		return result;
	}

	public boolean checkRule() {
		String temp = stack.pop();
		if (control.peek().content.equals("gamma") 
				&& temp.length() > 7
				&& temp.substring(0, 7).equals("$$tau::") 
				&& checkInt(stack.peek())){
			stack.push(temp);
			return true;
		}
		else{
			stack.push(temp);
			return false;
		}
			
	}
	
	private boolean checkInt(String op1) {
		if (op1.substring(0,5).equals("<INT:")){
			return true;
		}else{
			return false;
		}
	}

}
